﻿package nl.joeyvandijk
{
	import caurina.transitions.Tweener;
	import flash.display.Sprite;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.events.IEventDispatcher;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	
	public class Logo extends Sprite
	{
		private var loader:Loader;
		private var isLoading:Boolean = false;
		
		public function Logo()
		{
			loader = new Loader();
			addChild(loader);
		}
		
		public function load(input:String):void
		{
			if(loader != null)
			{
				deconfigureListeners(loader.contentLoaderInfo);
				
				if(isLoading)
				{
					loader.close();
				}				
				loader.unload();
			}
			configureListeners(loader.contentLoaderInfo);
			loader.load(new URLRequest(input));
			isLoading = true;
		}
		
		private function configureListeners(dispatcher:IEventDispatcher):void {
            dispatcher.addEventListener(Event.COMPLETE, loaded);
            dispatcher.addEventListener(Event.INIT, initHandler);
            dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            dispatcher.addEventListener(Event.OPEN, openHandler);
        }
		
		private function deconfigureListeners(dispatcher:IEventDispatcher):void {
            dispatcher.removeEventListener(Event.COMPLETE, loaded);
            dispatcher.removeEventListener(Event.INIT, initHandler);
            dispatcher.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            dispatcher.removeEventListener(Event.OPEN, openHandler);
        }
		
		private function initHandler(event:Event):void {
			this.alpha = 0;
        }

        private function ioErrorHandler(event:IOErrorEvent):void {
            trace("Could not open logo: " + loader.contentLoaderInfo.url);
        }

        private function openHandler(event:Event):void {
        }
		
		private function loaded(e:Event):void
		{
			isLoading = false;
			Tweener.removeTweens(this);
			Tweener.addTween(this,{alpha:1, time:1, transition:'easeOutExpo'});
		}			
	}
}